﻿using System.Collections.Generic;
using System.Linq;
using LINQtoFxCop.Core;
using Microsoft.FxCop.Sdk;

namespace LINQtoFxCop.Flaws.Implementation
{
  internal sealed class ImplementationDoNotCatchGeneralExceptionTypes : FlawsIntrospectionRule
  {
    private readonly HashSet<string> _generalExceptionTypes;

    public ImplementationDoNotCatchGeneralExceptionTypes()
      : base("ImplementationDoNotCatchGeneralExceptionTypes")
    {
      _generalExceptionTypes = new HashSet<string>
                                 {
                                   "Microsoft.FxCop.Sdk.ClassNode:System.Object",
                                   "Microsoft.FxCop.Sdk.ClassNode:System.Exception",
                                   "Microsoft.FxCop.Sdk.ClassNode:System.SystemException"
                                 };
    }
    protected override IEnumerable<QueryResult> Query()
    {
      return
        from method in Methods
        where method.Instructions.HasItemWhen(IsGeneralExceptionCatch)
        select Result(method);
    }

    private bool IsGeneralExceptionCatch(Instruction instruction)
    {
      return instruction.OpCode == OpCode._Catch && _generalExceptionTypes.Contains(instruction.Value.ToString());
    }
  }
}
